<?php


class incident_admin
{
	var $data= Array();
	var $items = Array();

	function incident_admin()
	{
		global $lang, $db, $properties;
		
		include_once('includes/addMessage.php');
		
		$q = 'SELECT c_title, c_id, COUNT(in_id) as incident_count, MAX(in_raisedtime) as incident_latest,
					(SELECT COUNT(*) FROM ' . INCIDENTS_TABLE . ' i, ' . DIVISIONS_TABLE . ' d WHERE d.d_champid = c_id AND i.in_division = d.d_id AND i.in_adminstatus < 3) as incident_open 
			  FROM ' . CHAMPIONSHIPS_TABLE . ', ' . JUDGES_TABLE . ', ' . DIVISIONS_TABLE . '
			  LEFT JOIN ' . INCIDENTS_TABLE . ' ON in_division = d_id
			  WHERE ia_user = ' . $_SESSION['valid_id'] . ' AND (c_id = ia_champ OR ia_champ = 0) AND c_incidents = 1 AND c_id = d_champid 
			  GROUP BY c_id
 			  ORDER BY c_lastRace DESC';
		
		$res = $db->sql_query($q);
		
		if($db->sql_numrows($res) > 0)
		{
			$this->items[] = new addMessage($lang['UserCPIncidentsAdminInfo'], $lang['UserCPIncidentsAdmin']);
			while ($row = $db->sql_fetchrow($res))
			{
				$this->data[] = $row;				
			}
		}
		else
		{
			$this->items[] = new addMessage($lang['UserCPIncidentsAdminNoPrivileges'],  
											'<a href="usercp.php?action=incidentadmin">' . $lang['UserCPIncidentsAdmin']  .'</a>');
		}
	}
	
	function render()
	{
		foreach($this->items as $value)
		{
			$value->render();
		}
		
		if( sizeof($this->data) > 0)
		{
			global $lang, $skin_dir;
			
			$type = 'IncidentChampionship';
			
			include $skin_dir . 'tpl/tableStart.tpl';	
			include $skin_dir . 'tpl/incidentAdminListHeader.tpl';	
			
			$on = 'off';
			
			foreach($this->data as $incident)
			{			
				if($incident['incident_count'] > 0)
				{
					$incident['incident_title'] = '<a href="usercp.php?action=incidentadmin&champ=' . $incident['c_id'] . '">' . $incident['c_title'] . '</a>';
				}
				else
				{
					$incident['incident_title'] = $incident['c_title'];
				}
				$incident['incident_count'] = $incident['incident_count'] . ' (' . $incident['incident_open'] . ')';
							
				include $skin_dir . 'tpl/incidentAdminListItem.tpl';
				
				$on = $on == 'on' ? 'off' : 'on';
				
			}
		
			include $skin_dir . 'tpl/tableEnd.tpl';	
		}
	}
}


class incident_admin_champ
{
	var $data= Array();
	var $items = Array();

	function incident_admin_champ($champ)
	{
		global $lang, $db, $properties;
				
		include_once('includes/addMessage.php');
		
		$q = 'SELECT e_id, e_title, t_fullTitle, c_title, c_id, COUNT(in_id) as incident_count, MAX(in_raisedtime) as incident_latest, 
					(SELECT COUNT(*) FROM ' . INCIDENTS_TABLE . ' WHERE in_event = e_id AND in_adminstatus < 3) as incident_open
			  FROM ' . CHAMPIONSHIPS_TABLE . ', ' . JUDGES_TABLE . ', ' . TRACKS_TABLE . ', ' . EVENTDATES_TABLE .  ', ' . EVENTS_TABLE . '
			  LEFT JOIN ' . INCIDENTS_TABLE . ' ON in_event = e_id
			  WHERE ia_user = ' . $_SESSION['valid_id'] . ' AND (c_id = ia_champ OR ia_champ = 0) AND ed_event = e_id AND c_incidents = 1 AND 
			  		c_id = e_championship AND t_id = e_track AND c_id = ' . $champ . ' AND ed_date < NOW() AND 
					ed_date = (SELECT min(ed_date) FROM ' . EVENTDATES_TABLE .  ' e2 WHERE e2.ed_event = e_id)
			  GROUP BY e_id
 			  ORDER BY ed_date DESC';

		$res = $db->sql_query($q);
		
		if($db->sql_numrows($res) > 0)
		{
			$champ_name = '';
			while ($row = $db->sql_fetchrow($res))
			{
				$this->data[] = $row;		
				if($champ_name == '')		
				{
					$champ_name = '<a href="usercp.php?action=incidentadmin">' . $lang['UserCPIncidentsAdmin'] . 
						  '</a> - <a href="usercp.php?action=incidentadmin&champ=' . $row['c_id'] . '">' . $row['c_title'] .'</a>';
				}
			}
			$this->items[] = new addMessage($lang['UserCPIncidentsAdminInfo'], $champ_name);
			
		}
		else
		{
			$this->items[] = new addMessage($lang['UserCPIncidentsAdminNoPrivileges'], $lang['UserCPIncidentsAdmin']);
		}
	}
	
	function render()
	{
		foreach($this->items as $value)
		{
			$value->render();
		}
		
		if( sizeof($this->data) > 0)
		{
			global $lang, $skin_dir;
			
			$type = 'IncidentEvent';
			
			include $skin_dir . 'tpl/tableStart.tpl';	
			include $skin_dir . 'tpl/incidentAdminListHeader.tpl';	
			
			$on = 'off';
			
			foreach($this->data as $incident)
			{					
				if($incident['incident_count'] > 0)
				{
					$incident['incident_title'] = '<a href="usercp.php?action=incidentadmin&event=' . $incident['e_id'] . '">' . $incident['e_title'] . ' ' . $incident['t_fullTitle'] . '</a>';	
				}
				else
				{
					$incident['incident_title'] = $incident['e_title'] . ' ' . $incident['t_fullTitle'];
				}
				$incident['incident_count'] = $incident['incident_count'] . ' (' . $incident['incident_open'] . ')';
							
				include $skin_dir . 'tpl/incidentAdminListItem.tpl';
				
				$on = $on == 'on' ? 'off' : 'on';
				
			}
			
			include $skin_dir . 'tpl/tableEnd.tpl';	
		}
	}
}


class incident_admin_event
{
	var $data= Array();
	var $items = Array();

	function incident_admin_event($event)
	{
		global $lang, $db, $properties;
		
		include_once('includes/addMessage.php');
		
		$q = 'SELECT in_id, e_title, c_title,c_id, e_id, d_title, in_raisedtime, in_race, in_lap, in_corner, in_replaytime, in_adminstatus
			  FROM ' . JUDGES_TABLE . ', ' . DIVISIONS_TABLE . ', ' . CHAMPIONSHIPS_TABLE . ', ' . INCIDENTS_TABLE .  ', ' . EVENTS_TABLE .  '
			  	    WHERE ia_user = ' . $_SESSION['valid_id'] . ' AND (c_id = ia_champ OR ia_champ = 0) AND c_incidents = 1 AND 
			  		d_champid = c_id and d_id = in_division AND in_event = e_id AND in_event = ' . $event . '
			  GROUP BY in_id
			  ORDER BY d_order ASC, in_race ASC, in_lap ASC, in_id ASC';

		$res = $db->sql_query($q);
		
		if($db->sql_numrows($res) > 0)
		{
						  
			$champ_name = '';
			$commentIDs = Array();
			while ($row = $db->sql_fetchrow($res))
			{
				$row = formatArrayOutput($row, false);
				$this->data[$row['in_id']] = $row;	
				$this->data[$row['in_id']]['in_drivers'] = Array();
				$this->data[$row['in_id']]['in_judgements'] = Array();
				$commentIDs[] = array("catagory" => 1, "item" => $row['in_id']);
				$commentIDs[] = array("catagory" => 2, "item" => $row['in_id']);
				
				if($champ_name == '')		
				{
					$champ_name = '<a href="usercp.php?action=incidentadmin">' . $lang['UserCPIncidentsAdmin'] . 
						  '</a> - <a href="usercp.php?action=incidentadmin&champ=' . $row['c_id'] . '">' . $row['c_title'] .
						  '</a> - <a href="usercp.php?action=incidentadmin&event=' . $row['e_id'] . '">' . $row['e_title'] .'</a>';
				}
			}
			$this->items[] = new addMessage($lang['UserCPIncidentsAdminInfo'], $champ_name);
			
			//get comment details
			include_once('includes/comments.php');
			
			$statsManager = new commentStatistics($commentIDs);
			$commentArray = $statsManager->getAllStats();
			
			foreach($commentArray as $commentStat)
			{
				//comments
				if($commentStat['co_catagory'] == 1)
				{
					$this->data[$commentStat['co_catagory_item']]['in_commentcount'] = $commentStat['co_count'];
				}
				//appeals
				else
				{
					$this->data[$commentStat['co_catagory_item']]['in_appealcount'] = $commentStat['co_count'];
				}
			}
			
			
			//get drivers involved.
			$q = 'SELECT pf_drivername, id_incident, id_driver, id_role
				  FROM  ' . DRIVERNAME_TABLE .  ', ' . INCIDENTS_TABLE .  ', ' . INCIDENTDRIVERS_TABLE .  '
				  WHERE in_id = id_incident AND user_id = id_driver AND in_event =  ' . $event . '
				  ORDER BY in_id ASC, id_role ASC, pf_drivername ASC';
			$res = $db->sql_query($q);
		
			while ($row = $db->sql_fetchrow($res))
			{
				$row = formatArrayOutput($row, false);
				$this->data[$row['id_incident']]['in_drivers'][] = $row;
			}
			
			
			//get judgements.
			$q = 'SELECT ar_incident, ad.pf_drivername as ar_adminname, ar_admin, ar_explanation, as_ruling, 
						 ar_ptspen, ar_weightpen, ar_driver, dr.pf_drivername as ar_drivername
				  FROM  ' . DRIVERNAME_TABLE .  ' dr, ' . INCIDENTS_TABLE .  ', ' . 
				  			INCIDENTADMINRULINGS_TABLE .  ', ' . INCIDENTADMINREVIEW_TABLE .  '
				  LEFT JOIN ' . DRIVERNAME_TABLE .  ' ad ON (ad.user_id = ar_admin)
				  WHERE dr.user_id = ar_driver AND as_id = ar_verdict AND 
				  		ar_incident = in_id AND in_event = ' . $event . '
				  ORDER BY in_id ASC, ar_drivername  ASC, ar_adminname ASC';
 
			$res = $db->sql_query($q);
		
			while ($row = $db->sql_fetchrow($res))
			{
				$row = formatArrayOutput($row, false);
				$this->data[$row['ar_incident']]['in_judgements'][] = $row;
			}
			
		}
		else
		{
			$this->items[] = new addMessage($lang['UserCPIncidentsAdminNoPrivileges'], $lang['UserCPIncidentsAdmin']);
		}
	}
	
	function render()
	{
		foreach($this->items as $value)
		{
			$value->render();
		}
		
		if( sizeof($this->data) > 0)
		{
			global $lang, $skin_dir;
			
			$type = 'IncidentEvent';
			
			include $skin_dir . 'tpl/tableStart.tpl';	
			include $skin_dir . 'tpl/incidentAdminEHeader.tpl';	
				
			$last_event = '';
			$on = 'off';
						
			foreach($this->data as $incident)
			{			
				$incident['title'] =  $incident['d_title'] . ': ' . $lang['ResultsRace'] . ' ' . $incident['in_race'];		
			
				if($last_event == $incident['title'])
				{
					$incident['remStart'] = '<!--';
					$incident['remEnd'] = '-->';
				}
				else
				{
					$incident['remStart'] = '';
					$incident['remEnd'] = '';
				}
				
				$incident['comments'] = '<a href="usercp.php?action=incidentadmin&mode=comments&incident=' . $incident['in_id'] . '">';
				if(isset($incident['in_commentcount']))
				{
					$incident['comments'] .= $incident['in_commentcount'] . ' ' . $lang['CommentTitle'];
				}
				else
				{
					$incident['comments'] .=  0 . ' ' . $lang['CommentTitle'];
				} 
				$incident['comments'] .= '</a><br><a href="usercp.php?action=incidentadmin&mode=appeal&incident=' . $incident['in_id'] . '">';
				
				if(isset($incident['in_appealcount']))
				{
					$incident['comments'] .= $incident['in_appealcount'] . ' ' . $lang['IncidentsAppealCommentsTitle'];
				}
				else
				{
					$incident['comments'] .= 0 . ' ' . $lang['IncidentsAppealCommentsTitle'] ;
				} 
				$incident['comments'] .= '</a>';
				
				$lineBreak = $last_event == '' ? '' : '<br><br>';
				$last_event = $incident['title'];
				$incident['title'] = $lineBreak . $incident['title'];
				
				$incident['id'] = '<a href="usercp.php?action=incidentadmin&incident=' . $incident['in_id'] . '">#'  . $incident['in_id'] . '</a>';
				$incident['details'] = $lang['IncidentLap'] . ': ' . $incident['in_lap'] . '<br>' . $lang['IncidentCorner'] . ': ' . $incident['in_corner']
										. '<br>' . $lang['IncidentReplayTime'] . ': ' . $incident['in_replaytime'];
				
				
				$incident['drivers'] = '';
				$atFault = 0;
				$victim = 0;
				foreach($incident['in_drivers'] as $driver)
				{
					if($atFault == 0 && $driver['id_role'] == 0)
					{
						$incident['drivers'] .= $lang['IncidentFault'][$driver['id_role']] . ': ';
						$atFault = 1;
					}
					else if($victim == 0 && $driver['id_role'] == 1)
					{
						$incident['drivers'] .= '<br>' . $lang['IncidentFault'][$driver['id_role']] . ': ';
						$victim = 1;
					}
					else
					{
						$incident['drivers'] .= ', ';
					}
					
					$incident['drivers'] .= '<a href="drivers.php?id=' . $driver['id_driver'] . '">' . $driver['pf_drivername'] . '</a>';
				}
				
				$incident['casestatus'] = $lang['IncidentStatus'][$incident['in_adminstatus']];
						
				$incident['judgements'] = '';
				
				if(sizeof($incident['in_judgements']) > 0)
				{
					foreach($incident['in_judgements'] as $judgement)
					{
						if($incident['in_adminstatus'] == 0 && $judgement['ar_admin'] != 0)
						{
							$incident['judgements'] .= '<a href="drivers.php?id=' . $judgement['ar_admin'] . '">' . $judgement['ar_adminname'] . '</a>: ';
							
							$penalty = '';
							if($judgement['ar_ptspen'] > 0  || $judgement['ar_weightpen'] > 0)
							{
								$penalty = '<font color="red">';
								$penalty .= $judgement['ar_ptspen'] > 0 ? $lang['IncidentPointsPenalty'] . ' ' . $judgement['ar_ptspen'] . $lang['ResultsPtsUnit'] . ' ' : '';
								$penalty .= $judgement['ar_weightpen'] > 0 ? $lang['IncidentWeightPenalty'] . ' ' . $judgement['ar_weightpen'] . $lang['ResultsWeightUnit'] : '';
								$penalty .= '</font>';
							}					
							$incident['judgements'] .= '<a href="drivers.php?id=' . $judgement['ar_driver'] . '">' . $judgement['ar_drivername'] . '</a>, ' 
														. $judgement['as_ruling'] . '.  <i>' . $judgement['ar_explanation'] . '. ' .  $penalty . '</i><br>';
						}
						else if($incident['in_adminstatus'] > 0 && $judgement['ar_admin'] == 0)
						{
							$penalty = '';
							if($judgement['ar_ptspen'] > 0  || $judgement['ar_weightpen'] > 0)
							{
								$penalty = '<font color="red">';
								$penalty .= $judgement['ar_ptspen'] > 0 ? $lang['IncidentPointsPenalty'] . ' ' . $judgement['ar_ptspen'] . $lang['ResultsPtsUnit'] . ' ' : '';
								$penalty .= $judgement['ar_weightpen'] > 0 ? $lang['IncidentWeightPenalty'] . ' ' . $judgement['ar_weightpen'] . $lang['ResultsWeightUnit'] : '';
								$penalty .= '</font>';
							}					
							$incident['judgements'] .= '<a href="drivers.php?id=' . $judgement['ar_driver'] . '">' . $judgement['ar_drivername'] . '</a>, ' 
														. $judgement['as_ruling'] . '.  <i>' . $judgement['ar_explanation'] . '. ' .  $penalty . '</i><br>';
						}
					}
				}
				else
				{
					$incident['judgements'] = $lang['IncidentNoJudgements'];
				}
				
				if($incident['in_adminstatus'] < 3)
				{
					$incident['judgements'] .= '<br><a href="usercp.php?action=incidentadmin&mode=reviews&incident=' . $incident['in_id'] . '">'  . 
											$lang['IncidentsAdminAddReview'] . '</a>';
				}
				
				include $skin_dir . 'tpl/incidentAdminEItem.tpl';
				
				$on = $on == 'on' ? 'off' : 'on';
							
			}
			
			include $skin_dir . 'tpl/tableEnd.tpl';	
		}
	}
}

class incident_admin_menu
{
	var $incident;

	function incident_admin_menu($incident)
	{
		$this->incident = $incident;
	}
	
	function render()
	{
		global $lang, $skin_dir;
		
		$profile_link = '<a href="usercp.php?action=incidentadmin&mode=details&incident=' . $this->incident . '">' . $lang['IncidentMenuDetails'] . '</a>';
		$comments_link = '<a href="usercp.php?action=incidentadmin&mode=comments&incident=' . $this->incident . '">' . $lang['IncidentMenuComments'] . '</a>';
		$appeal_link = '<a href="usercp.php?action=incidentadmin&mode=appeal&incident=' . $this->incident . '">' . $lang['IncidentMenuAppeals'] . '</a>';
		$reviews_link = '<a href="usercp.php?action=incidentadmin&mode=reviews&incident=' . $this->incident . '">' . $lang['IncidentMenuReviews'] . '</a>';
		$public_link = '<a href="usercp.php?action=incidentadmin&mode=public&incident=' . $this->incident . '">' . $lang['IncidentMenuPublic'] . '</a>';
		$drivers_link = '<a href="usercp.php?action=incidentadmin&mode=drivers&incident=' . $this->incident . '">' . $lang['Drivers'] . '</a>';
		
		include $skin_dir . 'tpl/incidentAdminEMenu.tpl';	
	}
}

class incident_admin_comments
{
	var $incident;
	var $items = Array();

	function incident_admin_comments($incident)
	{
		global $db, $properties;
		include_once('includes/addMessage.php');
		include_once 'includes/comments.php';
				
		//get general data
		$q = 'SELECT in_id, in_race, in_adminstatus, e_id, c_id, c_title, c_smallTitle, e_title, d_title,
					 DATE_ADD(in_raisedtime, INTERVAL ' . $properties['event_incident_reply'] . ' HOUR) > NOW() as comments_allowed
			  FROM  ' . INCIDENTS_TABLE .  ', ' . CHAMPIONSHIPS_TABLE . ', ' . DIVISIONS_TABLE . ', ' . EVENTS_TABLE . ', ' . JUDGES_TABLE . ' 
			  WHERE ia_user = ' . $_SESSION['valid_id'] . ' AND (c_id = ia_champ OR ia_champ = 0) AND 
			  		in_event = e_id AND in_division = d_id AND d_champid = c_id AND in_id = ' . $incident;

		$res = $db->sql_query($q);
	
		if ($row = $db->sql_fetchrow($res))
		{
			
			global $lang;
			
			$champ_name = '<a href="usercp.php?action=incidentadmin">' . $lang['UserCPIncidentsAdmin'] . 
						  '</a> - <a href="usercp.php?action=incidentadmin&champ=' . $row['c_id'] . '">' . $row['c_title'] .
						  '</a> - <a href="usercp.php?action=incidentadmin&event=' . $row['e_id'] . '">' . $row['e_title'] .
						  '</a> - <a href="usercp.php?action=incidentadmin&incident=' . $row['in_id'] . '">' . $lang['Incident'] . ' #' . $row['in_id']. '</a>';
			
			
			$qDr = 'SELECT user_id, pf_drivername 
					FROM ' . DRIVERNAME_TABLE . ', ' . INCIDENTS_TABLE . ', ' . INCIDENTDRIVERS_TABLE . ' 
					WHERE (user_id = in_reportee OR id_driver = user_id) AND in_id = id_incident AND id_incident = ' . $incident . '
					GROUP BY user_id
					ORDER BY pf_drivername';
					
			$resDr = $db->sql_query($qDr);
			$drivers = Array();
			
			while ($rowDr = $db->sql_fetchrow($resDr))
			{
				$drivers[] = $rowDr;
			}
			
			
			
			$this->items[] = new addMessage($lang['UserCPIncidentsAdminInfo'], $champ_name);
			$this->items[] = new incident_admin_menu($incident);
			
			//1 = incidents, $id = which incident comments to show, 0 = show comments directed to me or from me only
			$this->items[] = new listComments(1, $incident, $lang['CommentTitle'], 0); 
		
			if($row['in_adminstatus'] < 3)
			{
				$closed = '';
				if(! $row['comments_allowed'])
				{
					$closed = '<br>' . $lang['IncidentsAdminCommentsClosed'];
				}
				//1 = incidents, $id = which incident to add comment too, 'usercp... ' = which action to use (must show comments or call addComment on this page), default title for comment
				$this->items[] = new addComment(1, $incident, 'usercp.php?action=incidentadmin&mode=comments&incident=' . $incident, 
												str_replace('{ID}', $incident, $lang['IncidentCommentTitle']), 
												'', '','<br>' . $lang['IncidentsAdminComments'] . $closed, $drivers, false, 'user_id', 'pf_drivername', 380, 'GRC Admin'); 
			}
			else
			{
				$this->items[] = new addMessage($lang['IncidentsCaseClosed'], '');
			}
		}
		else
		{
			$this->items[] = new addMessage($lang['UserCPIncidentsAdminNoPrivileges'], $lang['UserCPIncidentsAdmin']);
		}
			
			
	}
	
	function render()
	{
		foreach($this->items as $value)
		{
			$value->render();
		}
	}
}

class incident_admin_drivers
{
	var $incident;
	var $items = Array();
	var $drivers = Array();
	var $enabled = '';
	var $newDrivers;

	function incident_admin_drivers($incident)
	{
		global $db, $properties, $lang;
		include_once('includes/addMessage.php');
		include_once 'includes/comments.php';
		
		$this->incident = $incident;
			
		if(isset($_POST['editRecord']))
		{
			$this->edit();
		}
		else if(isset($_POST['removeRecord']))
		{
			$this->delete();
		}
		else if(isset($_POST['addRecord']))
		{
			$this->add();
		}
			
		//get general data
		$q = 'SELECT in_id, in_race, in_adminstatus, e_id, c_id, c_title, c_smallTitle, e_title, d_title,
					 DATE_ADD(in_raisedtime, INTERVAL ' . $properties['event_incident_reply'] . ' HOUR) > NOW() as comments_allowed
			  FROM  ' . INCIDENTS_TABLE .  ', ' . CHAMPIONSHIPS_TABLE . ', ' . DIVISIONS_TABLE . ', ' . EVENTS_TABLE . ', ' . JUDGES_TABLE . ' 
			  WHERE ia_user = ' . $_SESSION['valid_id'] . ' AND (c_id = ia_champ OR ia_champ = 0) AND 
			  		 in_event = e_id AND in_division = d_id AND d_champid = c_id AND in_id = ' . $incident;

		$res = $db->sql_query($q);
	
		if ($row = $db->sql_fetchrow($res))
		{
			if($row['in_adminstatus'] == 3)
				$this->enabled = 'DISABLED';
		
			$champ_name = '<a href="usercp.php?action=incidentadmin">' . $lang['UserCPIncidentsAdmin'] . 
						  '</a> - <a href="usercp.php?action=incidentadmin&champ=' . $row['c_id'] . '">' . $row['c_title'] .
						  '</a> - <a href="usercp.php?action=incidentadmin&event=' . $row['e_id'] . '">' . $row['e_title'] .
						  '</a> - <a href="usercp.php?action=incidentadmin&incident=' . $row['in_id'] . '">' . $lang['Incident'] . ' #' . $row['in_id']. '</a>';
			
			$qDr = 'SELECT user_id, pf_drivername, id_role
					FROM ' . DRIVERNAME_TABLE . ' ,' . INCIDENTDRIVERS_TABLE . ' 
					WHERE id_driver = user_id AND id_incident = ' . $incident . '
					ORDER BY pf_drivername';
			$resDr = $db->sql_query($qDr);
			
			while ($rowDr = $db->sql_fetchrow($resDr))
			{
				$this->drivers[] = $rowDr;
			}
			
			$qDr = 'SELECT d.user_id, pf_drivername
					FROM ' . DRIVERNAME_TABLE . ' d, '  . USERSGROUPS_TABLE . ' u 
					WHERE d.user_id = u.user_id AND u.group_id = 3 AND u.user_id NOT IN 
						(SELECT id_driver FROM ' . INCIDENTDRIVERS_TABLE . ' WHERE id_incident = ' . $incident . ')
					ORDER BY pf_drivername';
			$resDr = $db->sql_query($qDr);
			
			while ($rowDr = $db->sql_fetchrow($resDr))
			{
				$this->newDrivers .= '<option value="' . $rowDr['user_id'] . '">' . $rowDr['pf_drivername'] . '</option>';
			}
			
			$this->items[] = new addMessage($lang['UserCPIncidentsAdminInfo'], $champ_name);
			$this->items[] = new incident_admin_menu($incident);
			$this->items[] = new addMessage($lang['IncidentsAdminDrivers'], $lang['Drivers']);
		}
		else
		{
			$this->items[] = new addMessage($lang['UserCPIncidentsAdminNoPrivileges'], $lang['UserCPIncidentsAdmin']);
		}
			
			
	}
	
	function edit()
	{
		if(isset($_POST['driver']) && is_numeric($_POST['driver']) && 
		   isset($_POST['role']) && is_numeric($_POST['role']))
		{
			global $db, $lang, $www_path;
			
			$q = 'SELECT d.user_id, pf_drivername, u.user_email 
				  FROM ' . DRIVERNAME_TABLE . ' d, ' . USERS_TABLE . ' u 
				  WHERE u.user_id = d.user_id AND u.user_id = ' . $_POST['driver'];
			$res = $db->sql_query($q);
			if ($row = $db->sql_fetchrow($res))
			{
				$q = 'UPDATE ' . INCIDENTDRIVERS_TABLE . '
					  SET id_role = ' . $_POST['role'] . '
					  WHERE id_incident = ' . $this->incident . ' AND
							id_driver = ' . $_POST['driver'];
				$res = $db->sql_query($q);
				
				include_once('includes/addMessage.php');
				
				//sucesfully updated driver - send notification email
				if($db->sql_affectedrows() > 0)
				{
					$this->items[] = new addMessage(str_replace('{entry}', '', $lang['AdminUpdated']), $lang['AdminUpdatedTitle']);
					
					include_once('includes/email.php');
					
					$email = new email('incident_adminedit', $row);
					$email->addReplacement('{INCIDENT_ID}' , $this->incident);
					$email->addReplacement('{EMAILADRESS}' , 'user_email', 1);
					$email->addReplacement('{DRIVERNAME}' , 'pf_drivername', 1);
					$email->addReplacement('{INCIDENTLINK}' , '<a href="' . $www_path . 'usercp.php?action=viewincident&id=' . $this->incident . '">' . 
																 $www_path . 'usercp.php?action=viewincident&id=' . $this->incident . '</a>' );
					$email->sendEmail();
				}
				else
				{
					$this->items[] = new addMessage($lang['DatabaseError'], $lang['DatabaseErrorTitle']);
				}
			}
		}
	}
	
	function add()
	{
		if(isset($_POST['driver']) && is_numeric($_POST['driver']) && 
		   isset($_POST['role']) && is_numeric($_POST['role']))
		{
			global $db, $lang, $www_path;
			
			$q = 'SELECT d.user_id, pf_drivername, u.user_email 
				  FROM ' . DRIVERNAME_TABLE . ' d, ' . USERS_TABLE . ' u 
				  WHERE u.user_id = d.user_id AND u.user_id = ' . $_POST['driver'];
			$res = $db->sql_query($q);
			if ($row = $db->sql_fetchrow($res))
			{
				$q = 'INSERT INTO ' . INCIDENTDRIVERS_TABLE . '
							(id_incident, id_driver, id_role)
					  VALUES (' . $this->incident . ', ' . $_POST['driver'] . ', ' . $_POST['role'] . ')';
				$res = $db->sql_query($q);
				
				include_once('includes/addMessage.php');
				
				//sucesfully updated driver - send notification email
				if($db->sql_affectedrows() > 0)
				{
					$this->items[] = new addMessage(str_replace('{entry}', '', $lang['AdminAdded']), $lang['AdminAddedTitle']);
					
					include_once('includes/email.php');
					
					$email = new email('incident_adminadd', $row);
					$email->addReplacement('{INCIDENT_ID}' , $this->incident);
					$email->addReplacement('{EMAILADRESS}' , 'user_email', 1);
					$email->addReplacement('{DRIVERNAME}' , 'pf_drivername', 1);
					$email->addReplacement('{INCIDENTLINK}' , '<a href="' . $www_path . 'usercp.php?action=viewincident&id=' . $this->incident . '">' . 
																 $www_path . 'usercp.php?action=viewincident&id=' . $this->incident . '</a>' );
					$email->sendEmail();
				}
				else
				{
					$this->items[] = new addMessage($lang['DatabaseError'], $lang['DatabaseErrorTitle']);
				}
			}
		}
	}
	
	function delete()
	{
		if(isset($_POST['driver']) && is_numeric($_POST['driver']))
		{
			global $db, $lang, $www_path;
			
			$q = 'SELECT d.user_id, pf_drivername, u.user_email 
				  FROM ' . DRIVERNAME_TABLE . ' d, ' . USERS_TABLE . ' u 
				  WHERE u.user_id = d.user_id AND u.user_id = ' . $_POST['driver'];
			$res = $db->sql_query($q);
			if ($row = $db->sql_fetchrow($res))
			{
				$q = 'DELETE FROM ' . INCIDENTDRIVERS_TABLE . '
					  WHERE id_incident = ' . $this->incident . ' AND id_driver = ' . $_POST['driver'];

				$res = $db->sql_query($q);
				
				include_once('includes/addMessage.php');
				
				//sucesfully updated driver - send notification email
				if($db->sql_affectedrows() > 0)
				{
					$this->items[] = new addMessage(str_replace('{entry}', '', $lang['AdminRemoved']), $lang['AdminRemovedTitle']);
					
					include_once('includes/email.php');
					
					$email = new email('incident_admindelete', $row);
					$email->addReplacement('{INCIDENT_ID}' , $this->incident);
					$email->addReplacement('{EMAILADRESS}' , 'user_email', 1);
					$email->addReplacement('{DRIVERNAME}' , 'pf_drivername', 1);
					$email->sendEmail();
				}
				else
				{
					$this->items[] = new addMessage($lang['DatabaseError'], $lang['DatabaseErrorTitle']);
				}
			}
		}
	}
	
	function render()
	{
		foreach($this->items as $value)
		{
			$value->render();
		}
		
		global $skin_dir, $lang;
		
		include $skin_dir . 'tpl/tableStart.tpl';
		
		$remStart = '';
		$remEnd = '';
		$updateButton = 'editRecord';
		$updateButtonText = $lang['EditButton'];
		$incident = $this->incident;
		$enabled = $this->enabled;
		
		foreach ($this->drivers as $driver)
		{
			$driverOption = '<option value="' . $driver['user_id'] . '">' . $driver['pf_drivername'] . '</option>';
			$roleOption = '';
			
			for($x = 0; $x < sizeof($lang['IncidentFault']); $x++)
			{
				$roleOption .= '<option value="' . $x . '" ' . 
								($x == $driver['id_role'] ? 'SELECTED' : '')
								. '>' . $lang['IncidentFault'][$x] . '</option>';
			}
			include $skin_dir . 'tpl/incidentAdminEditDriver.tpl';
		}
		
		$remStart = '<!--';
		$remEnd = '-->';
		$updateButton = 'addRecord';
		$updateButtonText = $lang['AddButton'];
		
		$driverOption = $this->newDrivers;
		$roleOption = '';
		
		for($x = 0; $x < sizeof($lang['IncidentFault']); $x++)
		{
			$roleOption .= '<option value="' . $x . '">' . $lang['IncidentFault'][$x] . '</option>';
		}
		
		include $skin_dir . 'tpl/tableEnd.tpl';
		
		$addDriver = new addMessage($lang['IncidentsAdminAddDriverInfo'], $lang['IncidentsAdminAddDriver']);
		$addDriver->render();
		
		include $skin_dir . 'tpl/tableStart.tpl';
		
		include $skin_dir . 'tpl/incidentAdminEditDriver.tpl';
		
		
		include $skin_dir . 'tpl/tableEnd.tpl';
	}
}

class incident_admin_appeal
{
	var $incident;

	function incident_admin_appeal($incident)
	{
		global $db, $properties;
		include_once('includes/addMessage.php');
		include_once 'includes/comments.php';
				
		//get general data
		$q = 'SELECT in_id, in_race, in_adminstatus, c_id, e_id, c_title, c_smallTitle, e_title, d_title,
					 DATE_ADD(in_raisedtime, INTERVAL ' . $properties['event_incident_reply'] . ' HOUR) > NOW() as comments_allowed
			  FROM  ' . INCIDENTS_TABLE .  ', ' . CHAMPIONSHIPS_TABLE . ', ' . DIVISIONS_TABLE . ', ' . EVENTS_TABLE . ', ' . JUDGES_TABLE . ' 
			  WHERE ia_user = ' . $_SESSION['valid_id'] . ' AND (c_id = ia_champ OR ia_champ = 0) AND 
			  		in_event = e_id AND in_division = d_id AND d_champid = c_id AND in_id = ' . $incident;

		$res = $db->sql_query($q);
	
		if ($row = $db->sql_fetchrow($res))
		{
			
			global $lang;
			
			$champ_name = '<a href="usercp.php?action=incidentadmin">' . $lang['UserCPIncidentsAdmin'] . 
						  '</a> - <a href="usercp.php?action=incidentadmin&champ=' . $row['c_id'] . '">' . $row['c_title'] .
						  '</a> - <a href="usercp.php?action=incidentadmin&event=' . $row['e_id'] . '">' . $row['e_title'] .
						  '</a> - <a href="usercp.php?action=incidentadmin&incident=' . $row['in_id'] . '">' . $lang['Incident'] . ' #' . $row['in_id']. '</a>';
			
			
			$qDr = 'SELECT user_id, pf_drivername 
					FROM ' . DRIVERNAME_TABLE . ', ' . INCIDENTS_TABLE . ', ' . INCIDENTDRIVERS_TABLE . ' 
					WHERE (user_id = in_reportee OR id_driver = user_id) AND in_id = id_incident AND id_incident = ' . $incident . '
					GROUP BY user_id
					ORDER BY pf_drivername';
			$resDr = $db->sql_query($qDr);
			$drivers = Array();
			
			while ($rowDr = $db->sql_fetchrow($resDr))
			{
				$drivers[] = $rowDr;
			}
			
			
			
			$this->items[] = new addMessage($lang['UserCPIncidentsAdminInfo'], $champ_name);
			$this->items[] = new incident_admin_menu($incident);
			
			//1 = incidents, $id = which incident comments to show, 0 = show comments directed to me or from me only
			$this->items[] = new listComments(2, $incident, $lang['IncidentsAppealCommentsTitle'], 0); 
		
			if($row['in_adminstatus'] < 3)
			{
				$closed = '';
				if(! $row['comments_allowed'])
				{
					$closed = '<br>' . $lang['IncidentsAdminCommentsClosed'];
				}
				//1 = incidents, $id = which incident to add comment too, 'usercp... ' = which action to use (must show comments or call addComment on this page), default title for comment
				$this->items[] = new addComment(2, $incident, 'usercp.php?action=incidentadmin&mode=appeal&incident=' . $incident, 
												str_replace('{ID}', $incident, $lang['IncidentAppealTitle']), 
												'', '','<br>' . $lang['IncidentsAdminComments'] . $closed, $drivers, false, 'user_id', 'pf_drivername', 380, 'GRC Admin'); 
			}
			else
			{
				$this->items[] = new addMessage($lang['IncidentsCaseClosed'], '');
			}
		}
		else
		{
			$this->items[] = new addMessage($lang['UserCPIncidentsAdminNoPrivileges'], $lang['UserCPIncidentsAdmin']);
		}
	}
	
	function render()
	{
		foreach($this->items as $value)
		{
			$value->render();
		}
	}
}


class incident_admin_reviews
{
	var $incident;
	var $reviews = Array();
	var $rulings = '';
	var $drivers = '';
	var $enabled = '';
	var $valid = true;

	function incident_admin_reviews($incident)
	{
		global $db, $properties, $lang;
		include_once('includes/addMessage.php');
		include_once 'includes/comments.php';
				
		$this->incident = $incident;
			
		if(isset($_POST['editRecord']))
		{
			$this->edit();
		}
		else if(isset($_POST['removeRecord']))
		{
			$this->delete();
		}
		else if(isset($_POST['addRecord']))
		{
			$this->add();
		}
		
		//get general data
		$q = 'SELECT in_id, in_race, in_adminstatus, c_title, e_id, c_id, c_smallTitle, e_title, d_title
			  FROM  ' . INCIDENTS_TABLE .  ', ' . CHAMPIONSHIPS_TABLE . ', ' . DIVISIONS_TABLE . ', ' . EVENTS_TABLE . ', ' . JUDGES_TABLE . ' 
			  WHERE ia_user = ' . $_SESSION['valid_id'] . ' AND (c_id = ia_champ OR ia_champ = 0) AND 
			  		in_event = e_id AND in_division = d_id AND d_champid = c_id AND in_id = ' . $incident;

		$res = $db->sql_query($q);
	
		if ($row = $db->sql_fetchrow($res))
		{
		
			if($row['in_adminstatus'] == 3)
				$this->enabled = 'DISABLED';
		
			$champ_name = '<a href="usercp.php?action=incidentadmin">' . $lang['UserCPIncidentsAdmin'] . 
						  '</a> - <a href="usercp.php?action=incidentadmin&champ=' . $row['c_id'] . '">' . $row['c_title'] .
						  '</a> - <a href="usercp.php?action=incidentadmin&event=' . $row['e_id'] . '">' . $row['e_title'] .
						  '</a> - <a href="usercp.php?action=incidentadmin&incident=' . $row['in_id'] . '">' . $lang['Incident'] . ' #' . $row['in_id']. '</a>';
			
			//get all the rulings possible
			$qRu = 'SELECT * FROM ' . INCIDENTADMINRULINGS_TABLE . ' ORDER BY as_id';
			$resRu = $db->sql_query($qRu);
			$rulings = Array();
			
			while ($rowRu = $db->sql_fetchrow($resRu))
			{
				$rowRu = formatArrayOutput($rowRu, true);
				$rulings[] = $rowRu;
				$pens = '';
				if($rowRu['as_ptspen'] == 1 && $rowRu['as_weightpen'] == 1)
				{
					$pens = ' - (' . $lang['ResultsPtsUnit'] . '/' . $lang['ResultsWeightUnit'] . ')';
				}
				else if($rowRu['as_ptspen'] == 1)
				{
					$pens = ' - (' . $lang['ResultsPtsUnit'] . ')';
				}
				else if($rowRu['as_weightpen'] == 1)
				{
					$pens = ' - (' . $lang['ResultsWeightUnit'] . ')';
				}
				$this->rulings .= '<option value="' . $rowRu['as_id'] . '">' . $rowRu['as_ruling'] . $pens . '</option>';
			}
			
			//get all the rulings possible
			$qDr = 'SELECT user_id, pf_drivername, id_role 
					FROM ' . DRIVERNAME_TABLE . ', ' . INCIDENTDRIVERS_TABLE . ' 
					WHERE user_id = id_driver AND id_incident = ' . $incident . ' AND user_id NOT IN 
						(SELECT ar_driver FROM ' . INCIDENTADMINREVIEW_TABLE . ' 
						 WHERE ar_admin = ' . $_SESSION['valid_id'] . ' AND ar_incident = ' . $incident . ')
					ORDER BY pf_drivername ASC';
			$resDr = $db->sql_query($qDr);
			
			while ($rowDr = $db->sql_fetchrow($resDr))
			{
				$this->drivers .= '<option value="' . $rowDr['user_id'] . '">' . 
									$rowDr['pf_drivername'] . ' ('  . $lang['IncidentFault'][$rowDr['id_role']] . 
									')</option>';
			}
			
			$qR = 'SELECT a.pf_drivername as ar_adminname, d.pf_drivername as ar_drivername, ar_admin, ar_driver,
						   ar_incident, ar_verdict, ar_explanation, ar_ptspen, ar_weightpen 
					FROM ' . INCIDENTADMINREVIEW_TABLE . ', ' . DRIVERNAME_TABLE . ' d, ' . DRIVERNAME_TABLE . ' a
					WHERE ar_admin = a.user_id AND ar_driver = d.user_id AND ar_incident = ' . $incident . '
					ORDER BY ar_adminname ASC, ar_drivername ASC';

			$resR = $db->sql_query($qR);
			$drivers = Array();
			
			while ($rowr = $db->sql_fetchrow($resR))
			{
				$rowr = formatArrayOutput($rowr, true);
				$rowr['adminOption'] = '<option value="' . $rowr['ar_admin'] . '">' . $rowr['ar_adminname'] . '</option>';
				$rowr['driverOption'] = '<option value="' . $rowr['ar_driver'] . '">' . $rowr['ar_drivername'] . '</option>';
				$rowr['rulingOption'] = '';
				foreach($rulings as $ruling)
				{
					$pens = '';
					if($ruling['as_ptspen'] == 1 && $ruling['as_weightpen'] == 1)
					{
						$pens = ' - (' . $lang['ResultsPtsUnit']. '/' . $lang['ResultsWeightUnit'] . ')';
					}
					else if($ruling['as_ptspen'] == 1)
					{
						$pens = ' - (' . $lang['ResultsPtsUnit'] . ')';
					}
					else if($ruling['as_weightpen'] == 1)
					{
						$pens = ' - (' . $lang['ResultsWeightUnit'] . ')';
					}
					$rowr['rulingOption'] .= '<option value="' . $ruling['as_id'] . '"' . 
												($rowr['ar_verdict'] == $ruling['as_id'] ? 'SELECTED' : '') . 
												'>' . $ruling['as_ruling'] . $pens . '</option>';
				}
				
				$this->reviews[] = $rowr;
			}
			
			
			
			$this->items[] = new addMessage($lang['UserCPIncidentsAdminInfo'], $champ_name);
			$this->items[] = new incident_admin_menu($incident);
			$this->items[] = new addMessage('', $lang['IncidentMenuReviews']);
			
		}
		else
		{
			$this->items[] = new addMessage($lang['UserCPIncidentsAdminNoPrivileges'], $lang['UserCPIncidentsAdmin']);
			$this->valid = false;
		}
	}
	
	function edit()
	{
		if(isset($_POST['driver']) && is_numeric($_POST['driver']) && 
		   isset($_POST['admin']) && is_numeric($_POST['admin']) && 
		   isset($_POST['verdict']) && is_numeric($_POST['verdict']) && 
		   isset($_POST['points']) && is_numeric($_POST['points']) && 
		   isset($_POST['weight']) && is_numeric($_POST['weight']) && 
		   isset($_POST['explanation']) && $_POST['explanation'] != '')
		{
			global $db, $lang, $www_path;
			include_once('includes/addMessage.php');
			
			$q = 'UPDATE ' . INCIDENTADMINREVIEW_TABLE . ', ' . INCIDENTADMINRULINGS_TABLE  . '
				  SET ar_verdict = ' . $_POST['verdict'] .  ', 
					  ar_explanation = "' . $_POST['explanation'] . '", 
					  ar_ptspen = '  . $_POST['points'] . ' * as_ptspen,
					  ar_weightpen = ' . $_POST['weight'] . ' * as_weightpen
				  WHERE as_id = ' . $_POST['verdict'] . ' AND ar_incident = ' . $this->incident . ' AND
				  		ar_driver = ' . $_POST['driver'] . ' AND ar_admin = ' . $_POST['admin'];
			$res = $db->sql_query($q);
			
			//sucesfully updated driver - send notification email
			if($db->sql_affectedrows() > 0)
			{
				$this->items[] = new addMessage(str_replace('{entry}', '', $lang['AdminUpdated']), $lang['AdminUpdatedTitle']);
			}
			else
			{
				$this->items[] = new addMessage($lang['DatabaseError'], $lang['DatabaseErrorTitle']);
			}
		}
	}
	
	function add()
	{
		if(isset($_POST['driver']) && is_numeric($_POST['driver']) && 
		   isset($_POST['admin']) && is_numeric($_POST['admin']) && 
		   isset($_POST['verdict']) && is_numeric($_POST['verdict']) && 
		   isset($_POST['points']) && is_numeric($_POST['points']) && 
		   isset($_POST['weight']) && is_numeric($_POST['weight']) && 
		   isset($_POST['explanation']) && $_POST['explanation'] != '')
		{
			global $db, $lang, $www_path;
			include_once('includes/addMessage.php');
			
			$q = 'INSERT INTO ' . INCIDENTADMINREVIEW_TABLE . ' 
						(ar_incident, ar_admin, ar_driver, ar_verdict, ar_explanation, ar_ptspen, ar_weightpen, ar_date)
				  SELECT ' . $this->incident . ', ' . $_POST['admin'] . ', ' . $_POST['driver'] . ', ' . $_POST['verdict'] . ', "' .
				  			 $_POST['explanation'] . '", ' . $_POST['points'] . ' * as_ptspen, ' . $_POST['weight'] . ' * as_weightpen, NOW()
				  FROM ' . INCIDENTADMINRULINGS_TABLE . '
				  WHERE as_id = ' . $_POST['verdict'];
			$res = $db->sql_query($q);
			
			//sucesfully updated driver - send notification email
			if($db->sql_affectedrows() > 0)
			{
				$this->items[] = new addMessage(str_replace('{entry}', '', $lang['AdminAdded']), $lang['AdminAddedTitle']);
			}
			else
			{
				$this->items[] = new addMessage($lang['DatabaseError'], $lang['DatabaseErrorTitle']);
			}
		}
	}
	
	function delete()
	{
		if(isset($_POST['admin']) && is_numeric($_POST['driver']))
		{
			global $db, $lang, $www_path;
			
			$q = 'DELETE FROM ' . INCIDENTADMINREVIEW_TABLE . '
				  WHERE ar_incident = ' . $this->incident . ' AND ar_driver = ' . $_POST['driver'] .'
				  		AND ar_admin = ' . $_POST['admin'];
			$db->sql_query($q);
			
			include_once('includes/addMessage.php');
			
			//sucesfully deleted the report
			if($db->sql_affectedrows() > 0)
			{
				$this->items[] = new addMessage(str_replace('{entry}', '', $lang['AdminRemoved']), $lang['AdminRemovedTitle']);
			}
			else
			{
				$this->items[] = new addMessage($lang['DatabaseError'], $lang['DatabaseErrorTitle']);
			}
		}
	}
	
	function render()
	{
		global $lang, $skin_dir;
		
		foreach($this->items as $value)
		{
			$value->render();
		}
		
		if($this->valid)
		{
			$remStart = '';
			$remEnd = '';
			$updateButton = 'editRecord';
			$updateButtonText = $lang['EditButton'];
			
			include $skin_dir . 'tpl/tableStart.tpl';
			foreach($this->reviews as $review)
			{
				$enabled = $review['ar_admin'] == $_SESSION['valid_id'] ? $this->enabled : "DISABLED";
				include $skin_dir . 'tpl/incidentAdminEditReview.tpl';
			}
			include $skin_dir . 'tpl/tableEnd.tpl';
			
			$enabled = $this->enabled;
			$review = Array();
			$review['adminOption'] = '<option value="' . $_SESSION["valid_id"] . '">' . $_SESSION["valid_driver"] . "</option>";
			$review['driverOption'] = $this->drivers;
			$review['rulingOption'] = $this->rulings;
			$review['ar_ptspen'] = 0;
			$review['ar_weightpen'] = 0;
			$review['ar_explanation'] = '';
			$review['ar_incident'] = $this->incident;
			
			$remStart = '<!--';
			$remEnd = '-->';
			$updateButton = 'addRecord';
			$updateButtonText = $lang['AddButton'];
				
			$addReview = new addMessage($lang['IncidentsAdminAddReviewInfo'], $lang['IncidentsAdminAddReview']);
			$addReview->render();
			
			include $skin_dir . 'tpl/tableStart.tpl';
			include $skin_dir . 'tpl/incidentAdminEditReview.tpl';
			include $skin_dir . 'tpl/tableEnd.tpl';
		}
	}
}


class incident_admin_public
{
	var $incident;
	var $reviews = Array();
	var $rulings = '';
	var $drivers = '';
	var $enabled = '';
	var $valid = true;

	function incident_admin_public($incident)
	{
		global $db, $properties, $lang;
		include_once('includes/addMessage.php');
		include_once 'includes/comments.php';
				
		$this->incident = $incident;
			
		if(isset($_POST['editRecord']))
		{
			$this->edit();
		}
		else if(isset($_POST['removeRecord']))
		{
			$this->delete();
		}
		else if(isset($_POST['addRecord']))
		{
			$this->add();
		}
		
		//get general data
		$q = 'SELECT in_id, in_race, in_adminstatus, c_title, c_smallTitle, c_id, e_id, e_title, d_title
			  FROM  ' . INCIDENTS_TABLE .  ', ' . CHAMPIONSHIPS_TABLE . ', ' . DIVISIONS_TABLE . ', ' . EVENTS_TABLE . ', ' . JUDGES_TABLE . ' 
			  WHERE ia_user = ' . $_SESSION['valid_id'] . ' AND (c_id = ia_champ OR ia_champ = 0) AND 
			  		in_event = e_id AND in_division = d_id AND d_champid = c_id AND in_id = ' . $incident;

		$res = $db->sql_query($q);
	
		if ($row = $db->sql_fetchrow($res))
		{
		
			if($row['in_adminstatus'] == 3)
				$this->enabled = 'DISABLED';
												
			$champ_name = '<a href="usercp.php?action=incidentadmin">' . $lang['UserCPIncidentsAdmin'] . 
						  '</a> - <a href="usercp.php?action=incidentadmin&champ=' . $row['c_id'] . '">' . $row['c_title'] .
						  '</a> - <a href="usercp.php?action=incidentadmin&event=' . $row['e_id'] . '">' . $row['e_title'] .
						  '</a> - <a href="usercp.php?action=incidentadmin&incident=' . $row['in_id'] . '">' . $lang['Incident'] . ' #' . $row['in_id']. '</a>';
			
			//get all the rulings possible
			$qRu = 'SELECT * FROM ' . INCIDENTADMINRULINGS_TABLE . ' ORDER BY as_id';
			$resRu = $db->sql_query($qRu);
			$rulings = Array();
			
			while ($rowRu = $db->sql_fetchrow($resRu))
			{
				$rowRu = formatArrayOutput($rowRu, true);
				$rulings[] = $rowRu;
				$pens = '';
				if($rowRu['as_ptspen'] == 1 && $rowRu['as_weightpen'] == 1)
				{
					$pens = ' - (' . $lang['ResultsPtsUnit'] . '/' . $lang['ResultsWeightUnit'] . ')';
				}
				else if($rowRu['as_ptspen'] == 1)
				{
					$pens = ' - (' . $lang['ResultsPtsUnit'] . ')';
				}
				else if($rowRu['as_weightpen'] == 1)
				{
					$pens = ' - (' . $lang['ResultsWeightUnit'] . ')';
				}
				$this->rulings .= '<option value="' . $rowRu['as_id'] . '">' . $rowRu['as_ruling'] . $pens . '</option>';
			}
			
			//get all the rulings possible
			$qDr = 'SELECT user_id, pf_drivername, id_role 
					FROM ' . DRIVERNAME_TABLE . ', ' . INCIDENTDRIVERS_TABLE . ' 
					WHERE user_id = id_driver AND id_incident = ' . $incident . ' AND user_id NOT IN 
						(SELECT ar_driver FROM ' . INCIDENTADMINREVIEW_TABLE . ' 
						 WHERE ar_admin = 0 AND ar_incident = ' . $incident . ')
					ORDER BY pf_drivername ASC';
			$resDr = $db->sql_query($qDr);
			
			while ($rowDr = $db->sql_fetchrow($resDr))
			{
				$this->drivers .= '<option value="' . $rowDr['user_id'] . '">' . 
									$rowDr['pf_drivername'] . ' ('  . $lang['IncidentFault'][$rowDr['id_role']] . 
									')</option>';
			}
			
			$qR = 'SELECT d.pf_drivername as ar_drivername, ar_driver,
						   ar_incident, ar_verdict, ar_explanation, ar_ptspen, ar_weightpen 
					FROM ' . INCIDENTADMINREVIEW_TABLE . ', ' . DRIVERNAME_TABLE . ' d
					WHERE ar_admin = 0 AND ar_driver = d.user_id AND ar_incident = ' . $incident . '
					ORDER BY ar_drivername ASC';
			$resR = $db->sql_query($qR);
			$drivers = Array();
			
			while ($rowr = $db->sql_fetchrow($resR))
			{
				$rowr = formatArrayOutput($rowr, true);
				$rowr['driverOption'] = '<option value="' . $rowr['ar_driver'] . '">' . $rowr['ar_drivername'] . '</option>';
				$rowr['rulingOption'] = '';
				foreach($rulings as $ruling)
				{
					$pens = '';
					if($ruling['as_ptspen'] == 1 && $ruling['as_weightpen'] == 1)
					{
						$pens = ' - (' . $lang['ResultsPtsUnit']. '/' . $lang['ResultsWeightUnit'] . ')';
					}
					else if($ruling['as_ptspen'] == 1)
					{
						$pens = ' - (' . $lang['ResultsPtsUnit'] . ')';
					}
					else if($ruling['as_weightpen'] == 1)
					{
						$pens = ' - (' . $lang['ResultsWeightUnit'] . ')';
					}
					$rowr['rulingOption'] .= '<option value="' . $ruling['as_id'] . '"' . 
												($rowr['ar_verdict'] == $ruling['as_id'] ? 'SELECTED' : '') . 
												'>' . $ruling['as_ruling'] . $pens . '</option>';
				}
				
				$this->reviews[] = $rowr;
			}
			
			
			
			$this->items[] = new addMessage($lang['UserCPIncidentsAdminInfo'], $champ_name);
			$this->items[] = new incident_admin_menu($incident);
			$this->items[] = new addMessage('', $lang['IncidentMenuPublic']);
			
		}
		else
		{
			$this->items[] = new addMessage($lang['UserCPIncidentsAdminNoPrivileges'], $lang['UserCPIncidentsAdmin']);
			$this->valid = false;
		}
	}
	
	function edit()
	{
		if(isset($_POST['driver']) && is_numeric($_POST['driver']) && 
		   isset($_POST['admin']) && is_numeric($_POST['admin']) && 
		   isset($_POST['verdict']) && is_numeric($_POST['verdict']) && 
		   isset($_POST['points']) && is_numeric($_POST['points']) && 
		   isset($_POST['weight']) && is_numeric($_POST['weight']) && 
		   isset($_POST['explanation']) && $_POST['explanation'] != '')
		{
			global $db, $lang, $www_path;
			include_once('includes/addMessage.php');
			
			$q = 'UPDATE ' . INCIDENTADMINREVIEW_TABLE . ', ' . INCIDENTADMINRULINGS_TABLE  . ', ' . INCIDENTS_TABLE . ', ' .
                                         LICENSES_TABLE . ', ' . CHAMPIONSHIPS_TABLE . ', ' . EVENTS_TABLE . '
				  SET ar_verdict = ' . $_POST['verdict'] .  ', 
					  ar_explanation = "' . $_POST['explanation'] . '", 
					  ar_ptspen = '  . $_POST['points'] . ' * as_ptspen,
					  ar_weightpen = ' . $_POST['weight'] . ' * as_weightpen,
					  ar_licensepoints = as_licensepoints,
					  ar_licenseexpiry =  DATE_ADD(ar_date, INTERVAL l_pointDuration MONTH)
				  WHERE as_id = ' . $_POST['verdict'] . ' AND ar_incident = ' . $this->incident . ' AND
				  	ar_driver = ' . $_POST['driver'] . ' AND ar_admin = 0 AND as_id = ar_verdict AND
                                        ar_incident = in_id AND in_event = e_id AND e_championship = c_id AND c_license = l_id';
			$res = $db->sql_query($q);
			
			//sucesfully updated driver - send notification email
			if($db->sql_affectedrows() > 0)
			{
				$this->items[] = new addMessage(str_replace('{entry}', '', $lang['AdminUpdated']), $lang['AdminUpdatedTitle']);
			}
			else
			{
				$this->items[] = new addMessage($lang['DatabaseError'], $lang['DatabaseErrorTitle']);
			}
		}
	}
	
	function add()
	{
		if(isset($_POST['driver']) && is_numeric($_POST['driver']) && 
		   isset($_POST['admin']) && is_numeric($_POST['admin']) && 
		   isset($_POST['verdict']) && is_numeric($_POST['verdict']) && 
		   isset($_POST['points']) && is_numeric($_POST['points']) && 
		   isset($_POST['weight']) && is_numeric($_POST['weight']) && 
		   isset($_POST['explanation']) && $_POST['explanation'] != '')
		{
			global $db, $lang, $www_path, $properties;
			include_once('includes/addMessage.php');
			
			$q = 'INSERT INTO ' . INCIDENTADMINREVIEW_TABLE . ' 
						(ar_incident, ar_admin, ar_driver, ar_verdict, ar_explanation, ar_ptspen,
                                                 ar_weightpen, ar_date, ar_licensepoints, ar_licenseexpiry)
				  SELECT ' . $this->incident . ', 0, ' . $_POST['driver'] . ', ' . $_POST['verdict'] . ', "' .
				  	     $_POST['explanation'] . '", ' . $_POST['points'] . ' * as_ptspen, ' . $_POST['weight'] .
                                             ' * as_weightpen, NOW(), as_licensepoints, DATE_ADD(NOW(), INTERVAL l_pointDuration MONTH)
				  FROM ' . INCIDENTADMINRULINGS_TABLE . ', ' . INCIDENTS_TABLE . ', ' .
                                           LICENSES_TABLE . ', ' . CHAMPIONSHIPS_TABLE . ', ' . EVENTS_TABLE . '
				  WHERE as_id = ' . $_POST['verdict'] . ' AND ' . $this->incident . ' = in_id AND
                                        in_event = e_id AND e_championship = c_id AND c_license = l_id';
			$res = $db->sql_query($q);
			
			//sucesfully added the review - send notification email
			if($db->sql_affectedrows() > 0)
			{
				$this->items[] = new addMessage(str_replace('{entry}', '', $lang['AdminAdded']), $lang['AdminAddedTitle']);
				
				$q = 'UPDATE ' . INCIDENTS_TABLE . ' 
					  SET in_adminstatus = 1
					  WHERE in_id = ' . $this->incident;
				$db->sql_query($q);
				
				include_once('includes/email.php');
				$q = 'SELECT d.user_id, pf_drivername, u.user_email 
						  FROM ' . DRIVERNAME_TABLE . ' d, ' . USERS_TABLE . ' u
						  WHERE u.user_id = d.user_id AND u.user_id = ' . $_POST['driver'];
				$res = $db->sql_query($q);
				if ($row = $db->sql_fetchrow($res))
				{
					$email = new email('incident_adminpadded', $row);
					$email->addReplacement('{INCIDENT_ID}' , $this->incident);
					$email->addReplacement('{EMAILADRESS}' , 'user_email', 1);
					$email->addReplacement('{DRIVERNAME}' , 'pf_drivername', 1);
					$email->addReplacement('{APPEAL_TIME}' , $properties['event_incident_appeal']);
					$email->addReplacement('{INCIDENTLINK}' , '<a href="' . $www_path . 'usercp.php?action=viewincident&id=' . $this->incident . '">' . 
															 $www_path . 'usercp.php?action=viewincident&id=' . $this->incident . '</a>' );
					$email->sendEmail();
				}
			}
			else
			{
				$this->items[] = new addMessage($lang['DatabaseError'], $lang['DatabaseErrorTitle']);
			}
		}
	}
	
	function delete()
	{
		if(isset($_POST['admin']) && is_numeric($_POST['driver']))
		{
			global $db, $lang, $www_path;
			
			$q = 'DELETE FROM ' . INCIDENTADMINREVIEW_TABLE . '
				  WHERE ar_incident = ' . $this->incident . ' AND ar_driver = ' . $_POST['driver'] .'
				  		AND ar_admin = 0';
			$db->sql_query($q);
			
			include_once('includes/addMessage.php');
			
			//sucesfully deleted the report
			if($db->sql_affectedrows() > 0)
			{
				$this->items[] = new addMessage(str_replace('{entry}', '', $lang['AdminRemoved']), $lang['AdminRemovedTitle']);
			}
			else
			{
				$this->items[] = new addMessage($lang['DatabaseError'], $lang['DatabaseErrorTitle']);
			}
		}
	}
	
	function render()
	{
		global $lang, $skin_dir;
		
		foreach($this->items as $value)
		{
			$value->render();
		}
		
		if($this->valid)
		{
			$remStart = '';
			$remEnd = '';
			$updateButton = 'editRecord';
			$updateButtonText = $lang['EditButton'];
			
			include $skin_dir . 'tpl/tableStart.tpl';
			foreach($this->reviews as $review)
			{
				$enabled = $this->enabled;
				include $skin_dir . 'tpl/incidentAdminEditPublic.tpl';
			}
			include $skin_dir . 'tpl/tableEnd.tpl';
			
			if($this->drivers == '')
			{
				$enabled = 'DISABLED';
			}
			else
			{
				$enabled = $this->enabled;
			}
			$review = Array();
			$review['driverOption'] = $this->drivers;
			$review['rulingOption'] = $this->rulings;
			$review['ar_ptspen'] = 0;
			$review['ar_weightpen'] = 0;
			$review['ar_explanation'] = '';
			$review['ar_incident'] = $this->incident;
			
			$remStart = '<!--';
			$remEnd = '-->';
			$updateButton = 'addRecord';
			$updateButtonText = $lang['AddButton'];
				
			$addReview = new addMessage($lang['IncidentsAdminAddPublicInfo'], $lang['IncidentsAdminAddReview']);
			$addReview->render();
			
			include $skin_dir . 'tpl/tableStart.tpl';
			include $skin_dir . 'tpl/incidentAdminEditPublic.tpl';
			include $skin_dir . 'tpl/tableEnd.tpl';
		}
	}
}

class incident_admin_profile
{
	var $details = '';
	var $items = Array();

	function incident_admin_profile($incident)
	{
		$this->incident = $incident;
		
		global $db, $lang;
		include_once('includes/addMessage.php');
		
		if(isset($_POST['saveDetails']))
		{
			$this->saveDetails();
		}
		
		//get general data
		$q = 'SELECT in_id, in_race, in_lap, in_replaytime, in_corner, c_id, e_id, in_explanation, in_reportee, c_title, 
					 c_smallTitle, e_title, d_title, date_format(in_raisedtime, "%M %e, %Y, %l:%i%p") as in_raisedtime,
					 in_adminstatus
			  FROM  ' . INCIDENTS_TABLE .  ', ' . JUDGES_TABLE . ', ' . CHAMPIONSHIPS_TABLE . ', ' . 
			  			DIVISIONS_TABLE . ', ' . EVENTS_TABLE . '
			  WHERE ia_user = ' . $_SESSION['valid_id'] . ' AND (c_id = ia_champ OR ia_champ = 0) AND 
			  		in_event = e_id AND in_division = d_id AND d_champid = c_id AND in_id = ' . $incident;

		$res = $db->sql_query($q);
	
		if ($row = $db->sql_fetchrow($res))
		{
			$row = formatArrayOutput($row, true);
			$this->details = $row;
			$champ_name = '<a href="usercp.php?action=incidentadmin">' . $lang['UserCPIncidentsAdmin'] . 
						  '</a> - <a href="usercp.php?action=incidentadmin&champ=' . $row['c_id'] . '">' . $row['c_title'] .
						  '</a> - <a href="usercp.php?action=incidentadmin&event=' . $row['e_id'] . '">' . $row['e_title'] .
						  '</a> - <a href="usercp.php?action=incidentadmin&incident=' . $row['in_id'] . '">' . $lang['Incident'] . ' #' . $row['in_id']. '</a>';
			
			$this->details['in_status'] = '';
			for($x = 0; $x < sizeof($lang['IncidentStatus']); $x++)
			{
				$this->details['in_status'] .= '<option value="' . $x . '"' . ($row['in_adminstatus'] == $x ? 'SELECTED' : '') . 
							 					 '>' . $lang['IncidentStatus'][$x] . '</option>';
			}
			
			$this->details['in_reportee'] = '';
			$qDr = 'SELECT d.user_id, d.pf_drivername 
					FROM ' . DRIVERNAME_TABLE . ' d 
					JOIN ' . USERSGROUPS_TABLE . ' g ON d.user_id = g.user_id AND g.group_id = 3
					ORDER BY pf_drivername';
			$resDr = $db->sql_query($qDr);
			while ($rowDr = $db->sql_fetchrow($resDr))
			{
				$this->details['in_reportee'] .= '<option value="' . $rowDr['user_id'] . '"' . ($row['in_reportee'] == $rowDr['user_id'] ? 'SELECTED' : '') . 
							 					 '>' . $rowDr['pf_drivername'] . '</option>';
			}
			
			$this->items[] = new addMessage($lang['UserCPIncidentsAdminInfo'], $champ_name);
			$this->items[] = new incident_admin_menu($incident);
			$this->items[] = new addMessage($lang['IncidentsAdminDetailsInfo'], $lang['IncidentMenuDetails']);
		}
		else
		{
			$this->items[] = new addMessage($lang['UserCPIncidentsAdminNoPrivileges'], $lang['UserCPIncidentsAdmin']);
		}
	}
	
	function saveDetails()
	{
		
		include_once('includes/addMessage.php');
		
		global $lang, $db, $www_path;
	
		if(isset($_POST['race']) && is_numeric($_POST['race']) && isset($_POST['lap']) && is_numeric($_POST['lap']) && 
		   isset($_POST['replaytime']) && $_POST['replaytime'] != '' && isset($_POST['corner']) && $_POST['corner'] != '' &&
		   isset($_POST['explanation']) && $_POST['explanation'] != '' && isset($_POST['reportee']) && is_numeric($_POST['reportee']) && 
		   isset($_POST['status']) && is_numeric($_POST['status']) && isset($_POST['orgStatus']) && is_numeric($_POST['orgStatus']))
		{
			$q = 'UPDATE ' . INCIDENTS_TABLE . '
				  SET in_race = ' . $_POST['race'] . ',
				  	  in_lap = ' . $_POST['lap'] . ',
					  in_adminstatus = ' .$_POST['status'] . ',
					  in_reportee = ' . $_POST['reportee'] . ',
					  in_replaytime = "' . $_POST['replaytime'] . '",
					  in_corner = "' . $_POST['corner'] . '",
					  in_explanation = "' . $_POST['explanation'] . '"
				  WHERE in_id = ' . $this->incident;
			$res = $db->sql_query($q);
			if($db->sql_affectedrows() > 0)
			{
				$this->items[] = new addMessage(str_replace('{entry}', '', $lang['AdminUpdated']), $lang['AdminUpdatedTitle']);
				
				//case status has been changed, inform people.
				if($_POST['orgStatus'] != $_POST['status'])
				{							
					include_once('includes/email.php');

					$q = 'SELECT d.user_id, pf_drivername, u.user_email 
						  FROM ' . DRIVERNAME_TABLE . ' d, ' . USERS_TABLE . ' u, ' . INCIDENTDRIVERS_TABLE . '
						  WHERE u.user_id = d.user_id AND u.user_id = id_driver AND id_incident = ' . $this->incident;
					$res = $db->sql_query($q);
					while ($row = $db->sql_fetchrow($res))
					{
						$email = new email('incident_adminstatus', $row);
						$email->addReplacement('{INCIDENT_ID}' , $this->incident);
						$email->addReplacement('{EMAILADRESS}' , 'user_email', 1);
						$email->addReplacement('{DRIVERNAME}' , 'pf_drivername', 1);
						$email->addReplacement('{ORGINALSTATUS}' , $lang['IncidentStatus'][$_POST['orgStatus']]);
						$email->addReplacement('{NEWSTATUS}' , $lang['IncidentStatus'][$_POST['status']]);
						$email->addReplacement('{INCIDENTLINK}' , '<a href="' . $www_path . 'usercp.php?action=viewincident&id=' . $this->incident . '">' . 
																 $www_path . 'usercp.php?action=viewincident&id=' . $this->incident . '</a>' );
						$email->sendEmail();
					}
				}
				
			}
			else
			{
				$this->items[] = new addMessage($lang['DatabaseError'], $lang['DatabaseErrorTitle']);
			}
		}
		elseif(isset($_POST['status']) && is_numeric($_POST['status']) && isset($_POST['orgStatus']) && is_numeric($_POST['orgStatus']))
		{
			$q = 'UPDATE ' . INCIDENTS_TABLE . '
				  SET in_adminstatus = ' .$_POST['status'] . '
				  WHERE in_id = ' . $this->incident;		  
			$res = $db->sql_query($q);
			if($db->sql_affectedrows() > 0)
			{
				$this->items[] = new addMessage(str_replace('{entry}', '', $lang['AdminUpdated']), $lang['AdminUpdatedTitle']);
				
				//case status has been changed, inform people.
				if($_POST['orgStatus'] != $_POST['status'])
				{							
					include_once('includes/email.php');

					$q = 'SELECT d.user_id, pf_drivername, u.user_email 
						  FROM ' . DRIVERNAME_TABLE . ' d, ' . USERS_TABLE . ' u, ' . INCIDENTDRIVERS_TABLE . '
						  WHERE u.user_id = d.user_id AND u.user_id = id_driver AND id_incident = ' . $this->incident;
					$res = $db->sql_query($q);
					while ($row = $db->sql_fetchrow($res))
					{
						$email = new email('incident_adminstatus', $row);
						$email->addReplacement('{INCIDENT_ID}' , $this->incident);
						$email->addReplacement('{EMAILADRESS}' , 'user_email', 1);
						$email->addReplacement('{DRIVERNAME}' , 'pf_drivername', 1);
						$email->addReplacement('{ORGINALSTATUS}' , $lang['IncidentStatus'][$_POST['orgStatus']]);
						$email->addReplacement('{NEWSTATUS}' , $lang['IncidentStatus'][$_POST['status']]);
						$email->addReplacement('{INCIDENTLINK}' , '<a href="' . $www_path . 'usercp.php?action=viewincident&id=' . $this->incident . '">' . 
																 $www_path . 'usercp.php?action=viewincident&id=' . $this->incident . '</a>' );
						$email->sendEmail();
					}
				}
				
			}
			else
			{
				$this->items[] = new addMessage($lang['DatabaseError'], $lang['DatabaseErrorTitle']);
			}
		}
		else
		{
			$this->items[] = new addMessage($lang['DatabaseError'], $lang['DatabaseErrorTitle']);
		}
	
	}
	
	
	function render()
	{
		foreach($this->items as $value)
		{
			$value->render();
		}
		
		global $lang, $skin_dir;
		
		if($this->details != '')
		{
			$incident = $this->details;
			$enabled = $incident['in_adminstatus'] == 3 ? 'DISABLED' : '';
			include $skin_dir . 'tpl/incidentAdminEditDetails.tpl';
		}
	}
}

class incident_admin_view
{
	var $items = Array();

	function incident_admin_view($incident)
	{		
		if(isset($_GET['mode']) && $_GET['mode'] == 'comments')
		{
			$this->items[] = new incident_admin_comments($incident);
		}
		else if(isset($_GET['mode']) && $_GET['mode'] == 'appeal')
		{
			$this->items[] = new incident_admin_appeal($incident);
		}
		else if(isset($_GET['mode']) && $_GET['mode'] == 'reviews')
		{
			$this->items[] = new incident_admin_reviews($incident);
		}
		else if(isset($_GET['mode']) && $_GET['mode'] == 'drivers')
		{
			$this->items[] = new incident_admin_drivers($incident);
		}
		else if(isset($_GET['mode']) && $_GET['mode'] == 'public')
		{
			$this->items[] = new incident_admin_public($incident);
		}
		else
		{
			$this->items[] = new incident_admin_profile($incident);
		}
		
	}
	
	function render()
	{
		foreach($this->items as $value)
		{
			$value->render();
		}
	}
}
?>